/*
 * @Author: 260156 260156@gree.com.cn
 * @Date: 2022-08-18 11:02:11
 * @LastEditors: 260156 260156@gree.com.cn
 * @LastEditTime: 2022-08-29 17:18:49
 * @FilePath: \gree-zst-web\src\utils\validate.ts
 * @Description:
 *
 * Copyright (c) 2022 by 260156 260156@gree.com.cn, All Rights Reserved.
 */
export const percentageReg = /^\d+(\.\d+)?%$/;
export const numberReg = /^\d+(\.\d+)?$/;

// 必填
export const requiredValidate = (trigger: string | string[] = "blur") => ({
  required: true,
  message: "必填",
  trigger,
});

// 日期必填
const dateValidate = (rule: any, value: any, cb: any) => {
  if (!value) {
    cb(new Error("必填"));
  } else {
    cb();
  }
};
export const requiredDateValidate = () => ({
  required: true,
  validator: dateValidate,
  trigger: "change",
});

// 长度限制
export const lengthValidate = (max: number, min: number = 0) => {
  const message =
    min === 0 ? `最多输入${max}个字符` : `请输入${min} - ${max}个字符`;
  return { max, message, trigger: "blur" };
};

// 百分数格式限制
export const percentageValidate = () => ({
  validator: (rule: any, value: any, cb: any) => {
    if (!percentageReg.test(value)) {
      cb(new Error("请输入百分数"));
    } else {
      cb();
    }
  },
  trigger: "blur",
});

// 数字格式限制
export const numberValidate = ({
  min,
  max,
}: { min?: number; max?: number } = {}) => ({
  validator: (rule: any, value: any, cb: any) => {
    if (!numberReg.test(value)) {
      return cb(new Error("请输入数值"));
    } else if (max && parseFloat(value) > max) {
      return cb(new Error(`请输入小于等于${max}的值`));
    } else if (min && parseFloat(value) < min) {
      return cb(new Error(`请输入大于等于${min}的值`));
    }
    return cb();
  },
  trigger: "blur",
});
